import importlib

import ActionHandlers

# tasks = [
#     {
#         "task": "task_name_1",
#         "action": {
#             "name": "click",
#             "params":{
#                 "x": 123,
#             }
#         },
#     },
#     {
#         "task": "task_name_2",
#         "action": {
#             "name": "ccc",
#             "params":{

#             }
#         },
#     },
#     {
#         "task": "task_name_3",
#         "action": {
#             "name": "click",
#             "params":{
#                 "x": 127773,
#             }
#         },
#         "callback":{
#             "name":"kanGuangGao"
#         },
#     },
# ]


def execute(task: dict):
    status = False
    try:
        action_name = task["action"]["name"]
        if "params" in task["action"]:
            action_params = task["action"]["params"]
        else:
            action_params = {}

        # 检查是否有对应的处理函数
        if function_exists(ActionHandlers, action_name):
            res = call_function(ActionHandlers, action_name, action_params)

            if "sleep" in task:
                ActionHandlers.execute_with_random_sleep(task["sleep"])

            if res or res == None:
                status = True
                if "callback" in task:
                    callback_name = task["callback"]["name"]
                    if "params" in task["callback"]:
                        callback_params = task["callback"]["params"]
                    else:
                        callback_params = {}
                    # 动态导入模块
                    my_module = importlib.import_module(callback_name)

                    # 调用函数
                    status = my_module.run(**callback_params) and not None
               

        else:
            print(f"Unknown action: {action_name}")
    except Exception as e:
        print(e)

    finally:
        return status


def function_exists(module, func_name):
    """
    检查模块中是否存在指定名称的函数。

    :param module: 模块对象
    :param func_name: 字符串，函数名
    :return: 布尔值，如果函数存在且可调用则返回True，否则返回False
    """
    func = getattr(module, func_name, None)
    return callable(func)


def call_function(module, func_name, params=None):
    """
    如果模块中存在指定名称的函数，则调用它，并传递关键字参数。

    :param module: 模块对象
    :param func_name: 字符串，函数名
    :param kwargs: 传递给函数的关键字参数
    """

    if function_exists(module, func_name):
        # 使用 ** 来解包 kwargs 字典作为关键字参数
        try:
            return getattr(module, func_name)(**params)
        except Exception as e:
            raise ValueError(f"{func_name}输入的参数或者参数个数错误！", e)
    else:
        print(
            f"Function {func_name} does not exist or is not callable in module {module.__name__}"
        )


def run_tasks(tasks: list, loop: int = 1, **kwargs):
    """
    运行任务
    loop:循环次数 0 表示无限循环 默认执行一次
    tasks:任务列表
    return:是否执行成功
    """
    finished = False
    # 循环次数
    loop_num = 1

    captured = kwargs.get("captured", True)

    if loop < 0:
        raise ValueError("loop 必须大于等于 0")

    if loop == 0:
        # 如果 loop 为 0，则设置为无限循环
        loop = float("inf")

    while True:
        count = 0
        # 截图

        if captured:
            # cv_img=screen.bitmap_to_cvimage()
            pass

        for task in tasks:
            res = execute(task)
            if res or res == None:
                count += 1
                print(
                    f"循环次数:{loop_num}  当前任务：{task['task']}   当前状态：{task['action']['name']} 当前执行次数：{count}  执行结果：成功！"
                )
        loop_num += 1
        if count == 0:
            finished = True
            break

        # 对于无限循环，这里不会减少 loop 的值
        if loop != float("inf"):
            loop -= 1
            if loop == 0:
                break

    return finished
